<template>
  <div>
    <!--     搜索条件-->
    <SearchForm @search="getTableData" :isSearchDisabled="isSearchDisabled" @reset="clearSearch">
      <el-col :span="8" :xs="24" v-show="$permiss[183]">
        <el-form-item :label="$t('所属租户')" prop="adminUserId">
          <el-select
              @change="tenantChange"
              style="width: 100%"
              v-model="page.adminUserId"
              clearable
          >
            <el-option
                v-for="item in tenantList"
                :key="item.adminUserId"
                :label="item.adminName"
                :value="item.adminUserId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('用户姓名')" prop="loanName">
          <el-input v-model="page.loanName" clearable></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('订单编号')" prop="loanRecordId">
          <el-input v-model="page.loanRecordId" clearable></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('手机号码')" prop="phone">
          <el-input v-model="page.phone" clearable></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('身份证')" prop="idCard">
          <el-input v-model="page.idCard" clearable></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('打款状态')" prop="approvalResult">
          <el-select
              style="width: 100%"
              v-model="page.approvalResult"
              clearable
          >
            <el-option
                v-for="item in statusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('用户状态')">
          <el-select style="width: 100%" v-model="page.isRepeatedBorrowing" clearable>
            <el-option :label="$t('复借')" :value="1"></el-option>
            <el-option :label="$t('初借')" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('交易流水')" prop="dcode">
          <el-input v-model="page.dcode"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24" v-show="$permiss[184]">
        <el-form-item :label="$t('APP名称')" prop="productName">
          <el-select
              style="width: 100%"
              v-model="page.productName"
              clearable
          >
            <el-option
                v-for="item in productList"
                :key="item.productId"
                :label="item.appName"
                :value="item.productName"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('打款类型')" prop="lendType">
          <el-select
              style="width: 100%"
              v-model="page.lendType"
              clearable
          >
            <el-option :label="$t('线下')" :value="1"></el-option>
            <el-option :label="$t('线上')" :value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('银行账号')" prop="debitCard">
          <el-input v-model="page.debitCard" clearable></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('申请时间')" prop="applyTimeValue">
          <el-date-picker
              v-model="page.applyTimeValue"
              style="width: 100%"
              type="daterange"
              unlink-panels
              value-format="yyyy-MM-dd"
              range-separator="~"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')"
          >
          </el-date-picker>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('打款时间')" prop="paymentTimeValue">
          <el-date-picker
              v-model="page.paymentTimeValue"
              style="width: 100%"
              value-format="yyyy-MM-dd"
              type="daterange"
              unlink-panels
              range-separator="~"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')"
          >
          </el-date-picker>
        </el-form-item>
      </el-col>
    </SearchForm>

    <el-card shadow="never" style="margin-top: 10px">
      <el-row :gutter="24" style="margin: 0 0 10px 0;line-height: 32px;text-align: right" v-show="$permiss[180]">
        <!--        <el-col :span="12">-->
        <!--          <el-link type="primary" :underline="false">-->
        <!--            <span style="font-size: 18px">-->
        <!--              {{ $t("打款总金额") }} : {{ totalAmount.laterAmount }}-->
        <!--            </span>-->
        <!--          </el-link>-->
        <!--        </el-col>-->
        <el-button
            type="primary"
            @click="exportsExcel"
            :loading="exportsLoading"
        >{{ $t("导出") }}
        </el-button>
      </el-row>
      <Table
          ref="table"
          :loading="tableLoading"
          max-height="600px"
          :table-data="tableData"
          :page="page"
          :table-column="tableColumn"
          @handleSizeChange="handleSizeChange"
          @handleCurrentChange="handleCurrentChange"
      >
        <template slot="dealState" slot-scope="{ row }">
          {{
            row.dealState === 21  ? $t("已打款")  : (row.dealState === 12 || row.dealState === 0) ? $t("待打款")  : row.dealState === 11  ? $t("打款中")  : ""
          }}
        </template>
        <template slot="isRepeatedBorrowing" slot-scope="{row}">
          {{ row.isRepeatedBorrowing === 1 ? $t('复借') : $t('初借') }}
        </template>
        <template slot-scope="{ row }" slot="handle">
          <div v-if="row.dealState !== 11 && row.dealState !== 21">
            <el-button
                type="text"
                @click="tableRows('online', row)"
                v-show="$permiss[593]"
            >{{ $t("线上") }}
            </el-button
            >
            <el-button
                type="text"
                @click="tableRows('offline', row)"
                v-show="$permiss[181] && row.dealState !== $t('打款中')"
            >{{ $t("线下") }}
            </el-button>
            <el-button
                type="text"
                @click="closeOrder(row)"
                v-show="$permiss[214] && row.dealState !== 11"
            >
              {{ $t("关闭订单") }}
            </el-button>
          </div>
        </template>
      </Table>
    </el-card>
    <!--    线上打款-->
    <Dialog
        :title="$t('线上打款')"
        :visible.sync="onlineVisible"
        :confirm-loading="onlineLoading"
        @cancel="onlineVisible = false"
        width="30%"
        @confirm="onlineConfirm"
    >
      <el-form label-width="80px">
        <el-form-item :label="$t('订单编号')">
          <div style="line-height: 32px">
            {{ tableRowsList.loanRecordId }}
          </div>
        </el-form-item>
        <el-form-item :label="$t('用户姓名')">
          <div style="line-height: 32px">
            {{ tableRowsList.name }}
          </div>
        </el-form-item>
        <el-form-item :label="$t('手机号码')">
          <div style="line-height: 32px">
            {{ tableRowsList.phoneNum }}
          </div>
        </el-form-item>
        <el-form-item :label="$t('打款金额')">
          <div style="line-height: 32px">
            {{ tableRowsList.toPayAmount }}
          </div>
        </el-form-item>
        <el-form-item :label="$t('打款渠道')">
          <el-select v-model="onlineForm.onlineChannelId" style="width: 100%;">
            <el-option v-for="item in onlineChannel" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </Dialog>
    <!--    线下打款-->
    <Dialog
        @cancel="offlineVisible = false"
        @confirm="offlineConfirm"
        :title="$t('线下打款')"
        :visible.sync="offlineVisible"
        :confirm-loading="offlineLoading"
        @close="clearForm"
    >
      <el-form label-width="100px" :model="offlineForm" ref="offlineForm">
        <el-form-item :label="$t('订单编号')">
          <div style="line-height: 32px">
            {{ tableRowsList.loanRecordId }}
          </div>
        </el-form-item>
        <el-form-item :label="$t('用户姓名')">
          <div style="line-height: 32px">
            {{ tableRowsList.name }}
          </div>
        </el-form-item>
        <el-form-item :label="$t('手机号码')">
          <div style="line-height: 32px">
            {{ tableRowsList.phoneNum }}
          </div>
        </el-form-item>
        <el-form-item :label="$t('打款金额')">
          <div style="line-height: 32px">
            {{ tableRowsList.toPayAmount }}
          </div>
        </el-form-item>
        <el-form-item
            :label="$t('打款银行')"
            prop="bank"
            :rules="[{ required: true, message: $t('请选择打款银行') }]"
        >
          <el-select v-model="offlineForm.bank">
            <el-option
                v-for="item in backList"
                :key="item.bankAccount"
                :label="item.alias"
                :value="item.alias"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
            :label="$t('打款时间')"
            prop="date"
            :rules="[{ required: true, message: $t('请选择打款时间') }]"
        >
          <el-date-picker
              :pickerOptions="{
              disabledDate(time) {
                return time.getTime() > Date.now();
              },
            }"
              value-format="yyyy-MM-dd HH:mm:ss"
              v-model="offlineForm.date"
              type="datetime"
              :placeholder="$t('选择日期时间')"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>

<script>
import {dateFormatSection, deepClone, defaultTimeDate} from "@/utils/tools";
import {export_json_to_excel} from "@/utils/exportExcel";
import {
  paymentList,
  paymentAmountTotal,
  onLinePaymentAmount,
  paymentAmount,
  closeOrder,
  exportPaymentList
} from '@/api/finance'
import {selectProduct, selectTenant,} from "@/api/system";
import {onlineChannelList, fetchPayBank} from '@/api/pay'

export default {
  name: "paymentList",
  data() {
    const {$permiss} = this;
    return {
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        applyTimeValue: defaultTimeDate(2)
      },
      tableLoading: false,
      totalAmount: {
        laterAmount: 0,
        total: 0,
      },
      tableData: [],
      tenantList: [],
      productList: [],
      statusList: [
        {label: this.$t("待打款"), value: 1},
        {label: this.$t("已打款"), value: 2},
      ],
      onlineVisible: false,
      onlineLoading: false,
      offlineVisible: false,
      offlineLoading: false,
      onlineForm: {},
      onlineChannel: [],
      offlineForm: {},
      backList: [],
      tableColumn: [
        {
          label: this.$t("订单编号"),
          fixed: "left",
          align: "center",
          prop: "loanRecordId",
          minWidth: 150,
        },
        {
          label: this.$t("用户姓名"),
          prop: "name",
          align: "center",
          minWidth: 100,
        },
        {
          label: this.$t("手机号码"),
          prop: "phoneNum",
          align: "center",
          minWidth: 100,
        },
        {
          label: this.$t("身份证"),
          prop: "idNum",
          align: "center",
          minWidth: 100,
        },
        {
          label: this.$t("合同金额"),
          prop: "passAmount",
          align: "center",
          minWidth: 100,
        },
        {
          label: this.$t("打款金额"),
          prop: "laterAmount",
          align: "center",
          minWidth: 100,
        },
        {
          label: this.$t("打款状态"),
          prop: "dealState",
          slot: "dealState",
          align: "center",
          minWidth: 100,
        },
        {
          label: this.$t("银行名称"),
          prop: "cardIssuingBank",
          align: "center",
          minWidth: 150,
        },
        {
          label: this.$t("银行账号"),
          prop: "debitCard",
          align: "center",
          minWidth: 200,
        },
        {
          label: this.$t("交易流水"),
          prop: "dcode",
          align: "center",
          minWidth: 100,
        },
        {
          label: this.$t("失败原因"),
          prop: "failureReason",
          align: "center",
          minWidth: 100,
        },
        {
          label: this.$t("申请时间"),
          prop: "loanTime",
          align: "center",
          minWidth: 150,
        },
        {
          label: this.$t("用户状态"),
          prop: "isRepeatedBorrowing",
          slot: 'isRepeatedBorrowing',
          align: "center",
          minWidth: 100,
        },
        {
          label: this.$t("借款周期"),
          prop: "loanTerm",
          align: "center",
          minWidth: 100,
        },
        {
          label: this.$t("打款发起时间"),
          prop: "inputTime",
          align: "center",
          minWidth: 200,
        },
        {
          label: this.$t("打款结束时间"),
          prop: "dealTime",
          align: "center",
          minWidth: 200,
        },
        {
          label: this.$t("打款类型"),
          prop: "lendType",
          align: "center",
          minWidth: 100,
        },
        {
          label: this.$t("打款渠道"),
          prop: "channelCode",
          align: "center",
          minWidth: 100,
        },
        {
          label: this.$t("打款操作人"),
          prop: "inputUser",
          align: "center",
          minWidth: 100,
        },
        {
          label: this.$t("APP名称"),
          prop: "appName",
          align: "center",
          minWidth: 100,
        },
        {
          label: this.$t("所属租户"),
          align: "center",
          prop: "adminUserName",
          isHide: !this.$permiss[183],
        },
        {
          label: this.$t("操作"),
          fixed: "right",
          align: "center",
          slot: "handle",
          minWidth: 200,
          isHide: !$permiss[181] && !$permiss[214] && !$permiss[593],
        },
      ],
      exportsLoading: false,
      tableRowsList: {},
      isSearchDisabled: false
    };
  },

  mounted() {
    this.getTableData();
    this.getCompoentsApi();
  },
  computed: {},
  methods: {
    async getTableData() {
      this.tableLoading = true;
      this.isSearchDisabled = true
      const [loanTimeStart, loanTimeEnd] = dateFormatSection(this.page.applyTimeValue)
      const [datetimeStart, datetimeEnd] = dateFormatSection(this.page.paymentTimeValue)
      const params = {
        datetimeStart,
        datetimeEnd,
        loanTimeStart,
        loanTimeEnd,
        ...this.page
      }
      // 删除日期属性
      delete params.paymentTimeValue;
      delete params.applyTimeValue;
      // this.getTotalAmount(params);
      const res = await paymentList(params);
      if (res.code === 1 && res.data) {
        const {list,total} = res.data;
        this.tableData = list.map((item) => {
          item.lendType = item.lendType === "1" ? this.$t("线下") : item.lendType === "2" ? this.$t("线上") : '';
          return item;
        });
        this.page.total = total
        this.tableLoading = false;
        this.isSearchDisabled = false
      } else {
        this.tableLoading = false;
        this.isSearchDisabled = false
      }
    },
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.getTableData();
    },
    handleCurrentChange(val) {
      this.page.pageNum = val;
      this.getTableData();
    },
    async getCompoentsApi() {
      selectProduct().then(res => {
        this.productList = res.data
      });
      selectTenant().then(res => {
        this.tenantList = res.data
      });
    },
    tenantChange(value) {
      selectProduct({adminUserId: value}).then(res => {
        this.productList = res.data
        this.$set(this.page,'productName', null)
      })
    },
    // 获取打款总金额
    async getTotalAmount(params) {
      const res = await paymentAmountTotal(params);
      if (res.code === 1) {
        this.totalAmount.laterAmount = res.data || 0
      }
    },
    clearSearch() {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      };
      this.getTableData();
    },
    // 关闭订单
    async closeOrder(row) {
      this.$confirm(this.$t("关闭订单后不可撤销，确认关闭?"), this.$t("提示"), {
        confirmButtonText: this.$t("确认"),
        cancelButtonText: this.$t("取消"),
        type: "warning",
      }).then(async () => {
        const res = await closeOrder({
          loanRecordId: row.loanRecordId,
        });
        if (res.code === 1) {
          this.$message({
            type: "success",
            message: this.$t("该笔订单已关闭成功"),
          });
          this.getTableData();
        }
      });
    },
    async tableRows(type, row) {
      this.tableRowsList = deepClone(row);
      if (type === "online") {
        // 线上
        // 获取打款渠道
        await this.getOnlineChannel()
        this.onlineVisible = true;
      } else {
        // 线下
        // 获取打款银行
        await this.getpayBack(row);
        this.offlineVisible = true;
      }
    },
    async getOnlineChannel() {
      const res = await onlineChannelList({
        pageNum: 1,
        pageSize: 1000,
        productName: this.tableRowsList.productName,
        type: 1
      })
      if (res.code === 1) {
        this.onlineChannel = res.data.list
        this.$set(this.onlineForm, 'onlineChannelId', this.onlineChannel[0].id)
      }
    },
    async getpayBack(row) {
      this.backList = await fetchPayBank(row).then(res => res.data);
      if (this.backList && this.backList.length) {
        this.$set(this.offlineForm, "bank", this.backList[0].alias);
      }
    },
    clearForm() {
      this.offlineForm = {};
      this.$refs.offlineForm.resetFields();
    },
    // 导出excel
    async exportsExcel() {
      this.exportsLoading = true;
      const [loanTimeStart, loanTimeEnd] = dateFormatSection(this.page.applyTimeValue || [])
      const [datetimeStart, datetimeEnd] = dateFormatSection(this.page.paymentTimeValue || [])
      const params = {
        ...this.page,
        loanTimeStart,
        loanTimeEnd,
        datetimeStart,
        datetimeEnd,
      };
      delete params.paymentTimeValue;
      delete params.applyTimeValue;
      const res = await exportPaymentList(params);
      if (res.code === 1) {
        const headerData = [...this.tableColumn].filter(item => {
          const result = res.data.filter(i => {
            //过滤没有权限的字段
            return typeof i[item.prop] !== "undefined"
          })
          return result.length !== 0
        })
        const column = headerData.map(item => item.label)
        const filterVal = headerData.map(item => item.prop)
        const list = [...res.data].map((item) => {
          item.lendType = item.lendType === "1" ? this.$t("线下") : item.lendType === "2" ? this.$t("线上") : '';
          item.avoidAudit = item.avoidAudit === 1 ? this.$t("是") : item.avoidAudit === 2 ? this.$t("否") : "";
          item.dealState = item.dealState === 21 ? this.$t("已打款") : item.dealState === 12 ? this.$t("待打款") : item.dealState === 11 ? this.$t("打款中") : ""
          return item;
        }).map((v) => filterVal.map((j) => v[j]));
        const fileName = this.$t("打款列表");
        export_json_to_excel({
          header: column,
          data: list,
          filename: fileName,
        });
        this.exportsLoading = false;
      } else {
        this.exportsLoading = false;
      }
    },
    // 线上打款提交
    async onlineConfirm() {
      if (!this.onlineForm.onlineChannelId) return
      this.$confirm(this.$t("为避免造成损失，请确认是否进行该操作") + '?', this.$t("提示"), {
        type: "warning",
      }).then(async () => {
        this.onlineLoading = true;
        const res = await onLinePaymentAmount({
          loanRecordId: this.tableRowsList.loanRecordId,
          onlineChannelId: this.onlineForm.onlineChannelId
        }, {
          timeout: 0
        });
        if (res.code === 1) {
          this.$message.success(this.$t("线上打款发起成功,请耐心等待结果"));
          this.onlineVisible = false;
          this.onlineLoading = false;
          this.getTableData();
        } else {
          this.onlineLoading = false;
        }
      });

    },
    //线下还款提交
    offlineConfirm() {

      this.$refs.offlineForm.validate(async (v) => {
        if (v) {
          this.$confirm(this.$t("为避免造成损失，请确认是否进行该操作") + '?', this.$t("提示"), {
            type: "warning",
          }).then(async () => {
            this.offlineLoading = true
            const {bank, date} = this.offlineForm;
            const res = await paymentAmount({
              loanRecordId: this.tableRowsList.loanRecordId,
              payDate: date,
              payBank: bank,
            });
            if (res.code === 1) {
              this.$message.success(this.$t("打款成功"));
              this.clearForm();
              this.offlineVisible = false;
              this.offlineLoading = false
              this.getTableData();
            } else {
              this.offlineLoading = false
            }
          });
        }
      });
    },
  },
};
</script>

<style scoped>
</style>
